import traceback
import requests
from flask import Blueprint, current_app, request, jsonify
from flask_caching import Cache
from bs4 import BeautifulSoup
import pysnowball as ball
from app.models.news_model import News
from datetime import datetime

news_controller = Blueprint('news_controller', __name__)
cache = Cache(config={'CACHE_TYPE': 'simple'})

@news_controller.before_app_request
def init_cache():
    cache.init_app(current_app)

@news_controller.before_request
def log_request():
    current_app.logger.info(f"[NEWS] {request.method} {request.url}")

@news_controller.get('/sina')
def get_sina_news():
    """
    GET /news/sina
    返回新浪财经的新闻列表
    """
    cache_key = 'news:sina'
    data = cache.get(cache_key)
    if data:
        return jsonify({'code': 0, 'data': data})

    try:
        current_app.logger.info("[NEWS] 正在获取新浪财经新闻...")
        url = "http://zhibo.sina.com.cn/api/zhibo/feed?&page=1&page_size=100&zhibo_id=152"
        response = requests.get(url)
        response.raise_for_status()
        news_data = response.json()

        news_list = []
        for item in news_data['result']['data']['feed']['list']:
            news_item = {
                'id': item['id'],
                'title': item['rich_text'],
                'link': item['docurl'],
                'create_time': item['create_time'],
                'update_time': item['update_time'],
                'tags': [tag['name'] for tag in item['tag']],
            }
            news_list.append(news_item)

        cache.set(cache_key, news_list, timeout=300)
        return jsonify({'code': 0, 'data': news_list})

    except Exception as e:
        current_app.logger.error(f"[NEWS] 获取新浪财经新闻失败：\n{traceback.format_exc()}")
        return jsonify({'code': 500, 'msg': str(e)}), 500

@news_controller.get('/xueqiu')
def get_xueqiu_news():
    """
    GET /news/xueqiu
    返回雪球的新闻列表
    """
    cache_key = 'news:xueqiu'
    data = cache.get(cache_key)
    if data:
        return jsonify({'code': 0, 'data': data})

    try:
        ball.set_token('your_xueqiu_token')  # 替换为你的雪球token
        news_data = ball.news()

        news_list = []
        for item in news_data['data']['items']:
            news_list.append({
                'title': item['title'],
                'content': item['content'],
                'time': item['ctime'],
                'link': item['url']
            })

        cache.set(cache_key, news_list, timeout=300)
        return jsonify({'code': 0, 'data': news_list})

    except Exception as e:
        current_app.logger.error(f"[NEWS] 获取雪球新闻失败：\n{traceback.format_exc()}")
        return jsonify({'code': 500, 'msg': str(e)}), 500

@news_controller.get('/pbc')
def get_pbc_news():
    """
    GET /news/pbc
    返回央行官网的新闻列表
    """
    cache_key = 'news:pbc'
    data = cache.get(cache_key)
    if data:
        return jsonify({'code': 0, 'data': data})

    try:
        url = "http://www.pbc.gov.cn/"
        response = requests.get(url)
        response.raise_for_status()
        soup = BeautifulSoup(response.content, 'html.parser')

        news_list = []
        news_items = soup.select('.news-list li')
        for item in news_items:
            news_list.append({
                'title': item.select_one('a').text.strip(),
                'link': item.select_one('a')['href'],
                'time': item.select_one('.time').text.strip()
            })

        cache.set(cache_key, news_list, timeout=300)
        return jsonify({'code': 0, 'data': news_list})

    except Exception as e:
        current_app.logger.error(f"[NEWS] 获取央行官网新闻失败：\n{traceback.format_exc()}")
        return jsonify({'code': 500, 'msg': str(e)}), 500